// src/composables/useSkuGenerator.ts
import { ref, computed } from 'vue'
import type { Ref } from 'vue'
import type { SpecType, SkuItem, SkuSpec } from "@/api/types/product";

export function useSkuGenerator(specTypes: Ref<SpecType[]>) {
  const selectedSpecTypes = ref<(string | number)[]>([])
  const skuList = ref<SkuItem[]>([])

  // 计算属性：选中的规格类型
  const selectedSpecs = computed(() => {
    return specTypes.value.filter(spec => 
      selectedSpecTypes.value.includes(spec.id)
    )
  })

  // 生成 SKU 列表
  const generateSkus = (basePrice: number, baseStock: number) => {
    const valueArrays = selectedSpecs.value.map(spec =>
      spec.values.map(value => ({
        spec_type_id: spec.id,
        spec_name: spec.name,
        spec_value_id: value.id,
        value: value.value,
      }))
    )

    skuList.value = cartesianProduct(valueArrays).map((combo, index) => ({
      id: `sku-${Date.now()}-${index}`,
      specs: combo,
      sku_name: combo.map((item: SkuSpec) => item.value).join(" / "),
      price: basePrice,
      stock: baseStock,
      image: null,
    }))
  }

  // 笛卡尔积计算函数
  const cartesianProduct = (arrays: any[][]) => {
    return arrays.reduce(
      (acc, current) => 
        acc.flatMap(arr => 
          current.map(item => [...arr, item])
        ), 
      [[]]
    ).filter(arr => arr.length > 0)
  }

  // 重置 SKU 列表
  const resetSkus = () => {
    skuList.value = []
    selectedSpecTypes.value = []
  }

  return {
    selectedSpecTypes,
    skuList,
    generateSkus,
    resetSkus,
    cartesianProduct
  }
}